package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOutOrder(){
        log.info("处理超时订单: {}",LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> orderlist = ordersMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, time);
        if (orderlist != null && orderlist.size() > 0){
            for (Orders order : orderlist) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                ordersMapper.update(order);
            }
        }

    }

    /**
     * 处理自动确认收货订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processCompletedOrder(){
        log.info("处理派送中订单: {}",LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> orderlist = ordersMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);
        if (orderlist != null && orderlist.size() > 0){
            for (Orders order : orderlist) {
                order.setStatus(Orders.COMPLETED);
                ordersMapper.update(order);
            }
        }
    }
}
